package com.media.selector.camera

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.media.selector.BR
import com.media.selector.MediaSelector
import com.media.selector.R
import com.media.selector.databinding.FragmentCameraPreviewBinding
import com.media.selector.media.helper.MediaPath
import java.io.File

/**
 * date        ：2020/4/20
 * author      ：蒙景博
 * description ：
 */
class CameraPreviewFragment : Fragment() {

    companion object {
        const val PHOTO_URI = "photo_uri"
    }

    private var mPhotoUri: String = ""

    private lateinit var mBinding: FragmentCameraPreviewBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_camera_preview, container, false)
        mBinding.lifecycleOwner = this
        mBinding.setVariable(BR.data, this)
        return mBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mPhotoUri = arguments?.getString(PHOTO_URI) ?: ""
        mBinding.photoImage.setImageURI(Uri.parse(mPhotoUri))
    }

    fun onClick(view: View) {
         when(view.id) {
            R.id.photo_retake -> { // 重拍
                // 如果重新拍的话删除旧数据再返回上级页面
                File(mPhotoUri).delete()
                findNavController().navigateUp()
            }
            R.id.photo_select -> { // 选择
                with(requireActivity()) {
                    setResult(Activity.RESULT_OK, Intent().apply {
                        putExtra(MediaSelector.EXTRA_TAKE_PHOTO_STATE, true)
                        putExtra(MediaSelector.EXTRA_TAKE_PHOTO_RESULT, MediaPath.getFilePath(requireContext(), Uri.parse(mPhotoUri)))
                    })
                    finish()
                }
            }
        }
    }
}